import { createRouter, createWebHashHistory } from 'vue-router'
import useStore from '@/store'

const routes = [
  {
    path: '/login',
    component: () => import('@/views/login')
  },
  {
    path: '/',
    redirect: '/reg'
  },
  {
    path: '/reg',
    component: () => import('@/views/reg')
  },
  {
    path: '/:pathMatch(.*)',
    redirect: '/'
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})
const { user } = useStore()
router.beforeEach((to, from, next) => {
  if (user.token) {
    if (to.path.toLowerCase() === '/login') {
      next('/')
    } else {
      next()
    }
  } else if (to.path.toLowerCase() !== '/login') {
    next('/login')
  } else {
    next()
  }
})

export default router
